<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="iOS,源码,路由," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="本文主要分析 routable-ios 源码，通过本文可以了解路由的原理及使用。本文分为六个部分，从代码结构到具体的类依次介绍，文章最后会给出在项目中注册路由常用的方式。">
<meta name="keywords" content="iOS,源码,路由">
<meta property="og:type" content="article">
<meta property="og:title" content="routable-ios 源码解析">
<meta property="og:url" content="http://xgfe.github.io/2018/04/07/chenyu/routable-ios_sourceAnalysis/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="本文主要分析 routable-ios 源码，通过本文可以了解路由的原理及使用。本文分为六个部分，从代码结构到具体的类依次介绍，文章最后会给出在项目中注册路由常用的方式。">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/142772-7f18a54a0a327233.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-04-12T12:51:48.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="routable-ios 源码解析">
<meta name="twitter:description" content="本文主要分析 routable-ios 源码，通过本文可以了解路由的原理及使用。本文分为六个部分，从代码结构到具体的类依次介绍，文章最后会给出在项目中注册路由常用的方式。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/142772-7f18a54a0a327233.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> routable-ios 源码解析 | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              routable-ios 源码解析
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2018-04-07T13:12:00+08:00" content="2018-04-07">
            2018-04-07
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/chenyu/" itemprop="url" rel="index">
                  <span itemprop="name">chenyu</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/iOS/" rel="tag"><i class="icon-next-tags"></i>iOS</a>
            
              <a href="/tags/源码/" rel="tag"><i class="icon-next-tags"></i>源码</a>
            
              <a href="/tags/路由/" rel="tag"><i class="icon-next-tags"></i>路由</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><p>本文主要分析 <a href="https://github.com/clayallsopp/routable-ios" target="_blank" rel="external">routable-ios</a> 源码，通过本文可以了解路由的原理及使用。本文分为六个部分，从代码结构到具体的类依次介绍，文章最后会给出在项目中注册路由常用的方式。</p>
<a id="more"></a>
<h2 id="一、routable-ios-是什么？可以用来做什么？与之类似的框架还有哪些？"><a href="#一、routable-ios-是什么？可以用来做什么？与之类似的框架还有哪些？" class="headerlink" title="一、routable-ios 是什么？可以用来做什么？与之类似的框架还有哪些？"></a>一、routable-ios 是什么？可以用来做什么？与之类似的框架还有哪些？</h2><ul>
<li>routable-ios 是一个路由框架，由两个文件四个类组成，其中核心的类就一个。</li>
<li>可以很方便的实现 iOS 中<code>UIViewController</code>之间的跳转。跳转方式也可以灵活的设置，后面具体会讲到。</li>
<li>类似的框架还有 <a href="https://github.com/aaronbrethorst/ABRouter" target="_blank" rel="external">ABRouter</a> &amp; <a href="https://github.com/lightory/HHRouter" target="_blank" rel="external">HHRouter</a>。后期的文章也会对 HHRouter 做介绍。</li>
</ul>
<h2 id="二、routable-ios-中类的关系"><a href="#二、routable-ios-中类的关系" class="headerlink" title="二、routable-ios 中类的关系"></a>二、routable-ios 中类的关系</h2><p>&nbsp;&nbsp;了解类与类之间的关系，有助于理解整个框架。<code>Routable</code>继承自<code>UPRouter</code>，主要的功能都在<code>UPRouter</code>类中，路由主要的功能其实就两个：</p>
<ul>
<li>注册希望路由跳转的类及<code>URL</code></li>
<li>进行跳转</li>
</ul>
<p><img src="http://upload-images.jianshu.io/upload_images/142772-7f18a54a0a327233.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="routable-ios 类组织结构.png"></p>
<h2 id="三、routable-ios-如何使用"><a href="#三、routable-ios-如何使用" class="headerlink" title="三、routable-ios 如何使用"></a>三、routable-ios 如何使用</h2><ul>
<li>将<code>routable-ios</code>导入项目</li>
<li><p>注册路由：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[[Routable sharedRouter] map:@&quot;user/:name/:age&quot; toController:[UserController class]];</div></pre></td></tr></table></figure>
</li>
<li><p>调用路由进行跳转：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[[Routable sharedRouter] open:@&quot;user/chenyu/28&quot;];</div></pre></td></tr></table></figure>
</li>
<li><p>在 VC 中获取传递的参数</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">@implementation UserController</div><div class="line"></div><div class="line">- (id)initWithRouterParams:(NSDictionary *)params &#123;</div><div class="line">  if ((self = [self initWithNibName:nil bundle:nil])) &#123;</div><div class="line">    self.title = @&quot;User&quot;;</div><div class="line">      NSLog(@&quot;name: %@&quot;,[params objectForKey:@&quot;name&quot;]); //chenyu</div><div class="line">      NSLog(@&quot;age: %@&quot;,[params objectForKey:@&quot;age&quot;]);   //28</div><div class="line">  &#125;</div><div class="line">  return self;</div><div class="line">&#125;</div><div class="line"></div><div class="line">@end</div></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="四、routable-ios-中的核心类"><a href="#四、routable-ios-中的核心类" class="headerlink" title="四、routable-ios 中的核心类"></a>四、routable-ios 中的核心类</h2><p>&nbsp;&nbsp;核心类分别有：<code>Routable</code>，<code>UPRouterOptions</code>，<code>RouterParams</code>，<code>UPRouter</code></p>
<h3 id="1-Routable"><a href="#1-Routable" class="headerlink" title="1.Routable"></a>1.<code>Routable</code></h3><p>&nbsp;&nbsp;<code>Routable</code>继承自<code>UPRouter</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">+ (instancetype)sharedRouter; //提供单例方法，用来创建路由类</div><div class="line">+ (instancetype)newRouter;     //另一种创建路由的方式，一般不推荐，不是单例。</div></pre></td></tr></table></figure>
<h3 id="2-UPRouterOptions"><a href="#2-UPRouterOptions" class="headerlink" title="2.UPRouterOptions"></a>2.<code>UPRouterOptions</code></h3><p>&nbsp;&nbsp;<code>UPRouterOptions</code>继承自<code>NSObject</code>。首先看一下这个类提供的一些属性，我们就知道这个类是做什么的了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">@property (readwrite, nonatomic, getter=isModal) BOOL modal;  //是否是模态视图</div><div class="line">@property (readwrite, nonatomic) UIModalPresentationStyle presentationStyle;  //VC 显示的样式</div><div class="line">@property (readwrite, nonatomic) UIModalTransitionStyle transitionStyle;  //VC 出现时的动画</div><div class="line">@property (readwrite, nonatomic, strong) NSDictionary *defaultParams;  //默认的数据</div><div class="line">@property (readwrite, nonatomic, assign) BOOL shouldOpenAsRootViewController; //是否是根视图</div><div class="line"></div><div class="line">//.m 文件中的两个属性</div><div class="line">@property (readwrite, nonatomic, strong) Class openClass;  //注册的类</div><div class="line">@property (readwrite, nonatomic, copy) RouterOpenCallback callback;  //block 回调</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;通过以上内容，可以看到<code>UPRouterOptions</code>其实就是一个配置类，里面存储路由跳转时需要的一些数据，可以理解成一个辅助的类。这个类中提供了一系列的工厂方法，用来创建不同类型的对象，比如（只列举部分函数，其他同类型的函数还有很多，功能大体一致，只是某个配置项不同而已。）：</p>
<ul>
<li><p>全部使用默认配置</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">//Default construction; like [NSArray array]</div><div class="line">+ (instancetype)routerOptions &#123;</div><div class="line">  return [self routerOptionsWithPresentationStyle:UIModalPresentationNone</div><div class="line">                                  transitionStyle:UIModalTransitionStyleCoverVertical</div><div class="line">                                    defaultParams:nil</div><div class="line">                                           isRoot:NO</div><div class="line">                                          isModal:NO];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>传入所有参数创建对象</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">//Explicit construction</div><div class="line">+ (instancetype)routerOptionsWithPresentationStyle: (UIModalPresentationStyle)presentationStyle</div><div class="line">                                   transitionStyle: (UIModalTransitionStyle)transitionStyle</div><div class="line">                                     defaultParams: (NSDictionary *)defaultParams</div><div class="line">                                            isRoot: (BOOL)isRoot</div><div class="line">                                           isModal: (BOOL)isModal &#123;</div><div class="line">  UPRouterOptions *options = [[UPRouterOptions alloc] init];</div><div class="line">  options.presentationStyle = presentationStyle;</div><div class="line">  options.transitionStyle = transitionStyle;</div><div class="line">  options.defaultParams = defaultParams;</div><div class="line">  options.shouldOpenAsRootViewController = isRoot;</div><div class="line">  options.modal = isModal;</div><div class="line">  return options;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>自定义部分参数创建对象</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">//Custom class constructors, with heavier Objective-C accent</div><div class="line">+ (instancetype)routerOptionsAsModal &#123;</div><div class="line">  return [self routerOptionsWithPresentationStyle:UIModalPresentationNone</div><div class="line">                                  transitionStyle:UIModalTransitionStyleCoverVertical</div><div class="line">                                    defaultParams:nil</div><div class="line">                                           isRoot:NO</div><div class="line">                                          isModal:YES];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>剩余的基本就是一些快捷的方法及一些<code>setters</code>方法，可以查看源码。</p>
</li>
</ul>
<h3 id="3-RouterParams"><a href="#3-RouterParams" class="headerlink" title="3.RouterParams"></a>3.<code>RouterParams</code></h3><p>&nbsp;&nbsp;<code>RouterParams</code>继承自<code>NSObject</code>。<code>RouterParams</code>并没有在.h 文件中做声明，这个类只在<code>Routable</code>和<code>UPRouter</code>中的实现中才用到，而这三个类都在一个文件中，所以也没有必要出现在 .h 文件中。<br>首先看一下<code>RouterParams</code>的声明：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">@interface RouterParams : NSObject</div><div class="line"></div><div class="line">@property (readwrite, nonatomic, strong) UPRouterOptions *routerOptions;</div><div class="line">@property (readwrite, nonatomic, strong) NSDictionary *openParams; </div><div class="line">@property (readwrite, nonatomic, strong) NSDictionary *extraParams;</div><div class="line">@property (readwrite, nonatomic, strong) NSDictionary *controllerParams;</div><div class="line"></div><div class="line">@end</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;这个类的出现，主要作用是将跳转时匹配好的所有内容存起来，缓存到另一个字典中，未来再次跳转的时候，直接可以拿出来用，你也许会问，我们的路由不是在一个字典里吗，也可以直接拿出来用，为什么还要缓存，后续到源代码的地方会细说，为什么要缓存，为什么跳转的时候不是直接去 map 中寻找。</p>
<h3 id="4-UPRouter"><a href="#4-UPRouter" class="headerlink" title="4.UPRouter"></a>4.<code>UPRouter</code></h3><p>&nbsp;&nbsp;<code>UPRouter</code>继承自<code>NSObject</code>，首先看一下类的声明，删除了很多注释。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line">@interface UPRouter : NSObject</div><div class="line"></div><div class="line">/**</div><div class="line"> The UINavigationController instance which mapped UIViewControllers will be pushed onto.</div><div class="line"> */</div><div class="line">@property (readwrite, nonatomic, strong) UINavigationController *navigationController;</div><div class="line"></div><div class="line">- (void)pop;</div><div class="line">- (void)popViewControllerFromRouterAnimated:(BOOL)animated;</div><div class="line">- (void)pop:(BOOL)animated;</div><div class="line"></div><div class="line">@property (readwrite, nonatomic, assign) BOOL ignoresExceptions;</div><div class="line"></div><div class="line">- (void)map:(NSString *)format toCallback:(RouterOpenCallback)callback;</div><div class="line">- (void)map:(NSString *)format toCallback:(RouterOpenCallback)callback withOptions:(UPRouterOptions *)options;</div><div class="line">- (void)map:(NSString *)format toController:(Class)controllerClass;</div><div class="line">//注册路由，本篇主要分析的方法。上面的方法最终会调用这个方法，options 传入的是 nil</div><div class="line">- (void)map:(NSString *)format toController:(Class)controllerClass withOptions:(UPRouterOptions *)options;</div><div class="line"></div><div class="line"></div><div class="line">- (void)openExternal:(NSString *)url;</div><div class="line">- (void)open:(NSString *)url;</div><div class="line">- (void)open:(NSString *)url animated:(BOOL)animated;</div><div class="line">//路由跳转，本篇主要分析的方法。上面两个方法最终都会调用这个方法。</div><div class="line">- (void)open:(NSString *)url animated:(BOOL)animated extraParams:(NSDictionary *)extraParams;</div><div class="line"></div><div class="line">- (NSDictionary*)paramsOfUrl:(NSString*)url;</div><div class="line"></div><div class="line">@end</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">@interface UPRouter ()</div><div class="line"></div><div class="line">// 存储注册的路由</div><div class="line">@property (readwrite, nonatomic, strong) NSMutableDictionary *routes;</div><div class="line">// 缓存已跳转过的路由</div><div class="line">@property (readwrite, nonatomic, strong) NSMutableDictionary *cachedRoutes;</div><div class="line"></div><div class="line">@end</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;注册路由比较简单，就是将传入的<code>URL</code>作为 key，将<code>Class</code>作为值存入已初始化的<code>routes</code>中。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">- (void)map:(NSString *)format toController:(Class)controllerClass &#123;</div><div class="line">  [self map:format toController:controllerClass withOptions:nil];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (void)map:(NSString *)format toController:(Class)controllerClass withOptions:(UPRouterOptions *)options &#123;</div><div class="line">  if (!format) &#123;</div><div class="line">    @throw [NSException exceptionWithName:@&quot;RouteNotProvided&quot;</div><div class="line">                                   reason:@&quot;Route #format is not initialized&quot;</div><div class="line">                                 userInfo:nil];</div><div class="line">    return;</div><div class="line">  &#125;</div><div class="line">  //如果没有传入 options，则会创建一个默认的配置对象</div><div class="line">  if (!options) &#123;</div><div class="line">    options = [UPRouterOptions routerOptions];</div><div class="line">  &#125;</div><div class="line">  options.openClass = controllerClass;</div><div class="line">  [self.routes setObject:options forKey:format];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;路由跳转一共有三个比较重要的方法，首先看<code>open:animated:extraParams:</code>方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div></pre></td><td class="code"><pre><div class="line">- (void)open:(NSString *)url</div><div class="line">    animated:(BOOL)animated</div><div class="line"> extraParams:(NSDictionary *)extraParams</div><div class="line">&#123;</div><div class="line">  //获取路由跳转相关的参数，往下滑动，先看怎么获取的数据，看完下面的方法再回来看这个方法</div><div class="line">  RouterParams *params = [self routerParamsForUrl:url extraParams: extraParams];</div><div class="line">  UPRouterOptions *options = params.routerOptions;</div><div class="line">  </div><div class="line">  //好了，拿到数据了，开始跳转。先判断是否有回调，如果有的话，则去执行 block</div><div class="line">  if (options.callback) &#123;</div><div class="line">    RouterOpenCallback callback = options.callback;</div><div class="line">    callback([params controllerParams]);</div><div class="line">    return;</div><div class="line">  &#125;</div><div class="line">  //此处删除了判断 self.navigationController 是否存在的容错代码，无关紧要。</div><div class="line">  </div><div class="line">  //获取将要跳转的 VC，并且将我们传递的数据以字典的形式，传递给这个 VC</div><div class="line">  //controllerForRouterParams 这个方法比较简单，打断点进去看看就 OK 了。</div><div class="line">  UIViewController *controller = [self controllerForRouterParams:params];</div><div class="line">  </div><div class="line">  //判断当前是否有 presented 的 UIViewController，有的话要 dismiss，因为接下来要跳转或者 presentViewController</div><div class="line">  if (self.navigationController.presentedViewController) &#123;</div><div class="line">    [self.navigationController dismissViewControllerAnimated:animated completion:nil];</div><div class="line">  &#125;</div><div class="line">  </div><div class="line">  //是否是以模态的方式弹出 UIViewController</div><div class="line">  if ([options isModal]) &#123;</div><div class="line">    if ([controller.class isSubclassOfClass:UINavigationController.class]) &#123;</div><div class="line">      [self.navigationController presentViewController:controller</div><div class="line">                                              animated:animated</div><div class="line">                                            completion:nil];</div><div class="line">    &#125;</div><div class="line">    else &#123;</div><div class="line">      UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];</div><div class="line">      navigationController.modalPresentationStyle = controller.modalPresentationStyle;</div><div class="line">      navigationController.modalTransitionStyle = controller.modalTransitionStyle;</div><div class="line">      [self.navigationController presentViewController:navigationController</div><div class="line">                                              animated:animated</div><div class="line">                                            completion:nil];</div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  else if (options.shouldOpenAsRootViewController) &#123;</div><div class="line">    //设置根视图</div><div class="line">    [self.navigationController setViewControllers:@[controller] animated:animated];</div><div class="line">  &#125;</div><div class="line">  else &#123;</div><div class="line">    //直接 push 一个 UIViewController</div><div class="line">    [self.navigationController pushViewController:controller animated:animated];</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;获取路由跳转相关的参数方法（删除了一些容错处理的代码）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div></pre></td><td class="code"><pre><div class="line">- (RouterParams *)routerParamsForUrl:(NSString *)url extraParams: (NSDictionary *)extraParams &#123;</div><div class="line">  //如果缓存中已经有了（证明之前已经跳转过这个 VC），并且传递的参数没有变化。</div><div class="line">  //这里需要注意了，如果传递的参数你也不确定是不是没变化，最好给 extraParams 给个值，这样就不会走缓存了</div><div class="line">  //否则可能传递的数据变了，但是走的还是之前的缓存。</div><div class="line">  //如果 VC 之间不要传递数据，不用考虑这个问题</div><div class="line">  if ([self.cachedRoutes objectForKey:url] &amp;&amp; !extraParams) &#123;</div><div class="line">    return [self.cachedRoutes objectForKey:url];</div><div class="line">  &#125;</div><div class="line">  </div><div class="line">  NSArray *givenParts = url.pathComponents;</div><div class="line">  NSArray *legacyParts = [url componentsSeparatedByString:@&quot;/&quot;];</div><div class="line">  //这里判断传入的路由路径是否正确，如果传入这样的 &quot;iOS/app//first&quot; 路径，则会警告。</div><div class="line">  //也许你的路由路径是&quot;iOS/app&quot;，这样写你就少传了一个实参</div><div class="line">  if ([legacyParts count] != [givenParts count]) &#123;</div><div class="line">    NSLog(@&quot;Routable Warning - your URL %@ has empty path components - this will throw an error in an upcoming release&quot;, url);</div><div class="line">    givenParts = legacyParts;</div><div class="line">  &#125;</div><div class="line">  </div><div class="line">  //使用枚举的方式去匹配，这里不能从 self.routes 中通过 [self.routes objectForKey:@&quot;key&quot;] 的方式获取，</div><div class="line">  //因为注册的时候，你后面添加的是参数（形参），在跳转的时候传递的是数据（实参）。</div><div class="line">  //这里也就是为什么需要缓存的原因了，每次跳转都要枚举这个字典，缓存了以后时间复杂度直接降到了 O(1)。</div><div class="line">  __block RouterParams *openParams = nil;</div><div class="line">  [self.routes enumerateKeysAndObjectsUsingBlock:</div><div class="line">   ^(NSString *routerUrl, UPRouterOptions *routerOptions, BOOL *stop) &#123;</div><div class="line">     //routerUrl 是枚举到的 key，也是当时注册路由时添加进去的 url，routerOptions 是枚举到的 value</div><div class="line"></div><div class="line">     NSArray *routerParts = [routerUrl pathComponents];</div><div class="line">     //判断注册的路由地址和跳转的带参数的地址是否一致，最简单的办法就是判断他们包含的元素个数是否一致，如果一致，再做更详细的判断</div><div class="line">     if ([routerParts count] == [givenParts count]) &#123;</div><div class="line">       //如果个数一致，再判断是否匹配</div><div class="line">       NSDictionary *givenParams = [self paramsForUrlComponents:givenParts routerUrlComponents:routerParts];</div><div class="line">       if (givenParams) &#123;</div><div class="line">         //givenParams 存储的是路由地址中给的数据，再将 extraParams 一起传入 RouterParams，创建 RouterParams 的对象。</div><div class="line">         openParams = [[RouterParams alloc] initWithRouterOptions:routerOptions openParams:givenParams extraParams: extraParams];</div><div class="line">         *stop = YES;//结束遍历</div><div class="line">       &#125;</div><div class="line">     &#125;</div><div class="line">   &#125;];</div><div class="line">  </div><div class="line">  //如果没有匹配到路由</div><div class="line">  if (!openParams) &#123;</div><div class="line">    //用户设置了忽略异常，直接返回 nil，否则会走 @throw</div><div class="line">    if (_ignoresExceptions) &#123;</div><div class="line">      return nil;</div><div class="line">    &#125;</div><div class="line">    @throw [NSException exceptionWithName:@&quot;RouteNotFoundException&quot;</div><div class="line">                                   reason:[NSString stringWithFormat:ROUTE_NOT_FOUND_FORMAT, url]</div><div class="line">                                 userInfo:nil];</div><div class="line">  &#125;</div><div class="line">  //将我们辛辛苦苦封装好的路由相关的所有数据缓存起来，下次在走这个 url 的时候，直接取缓存中的数据，这就是为什么要缓存了。</div><div class="line">  //除非你传递的参数变了，那么一定传给 extraParams，相关方法检测到 extraParams 不为空，会重新组装数据。</div><div class="line">  [self.cachedRoutes setObject:openParams forKey:url];</div><div class="line">  return openParams;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">//判断注册的路由和跳转的路由是否一致</div><div class="line">- (NSDictionary *)paramsForUrlComponents:(NSArray *)givenUrlComponents</div><div class="line">                     routerUrlComponents:(NSArray *)routerUrlComponents &#123;</div><div class="line">  </div><div class="line">  __block NSMutableDictionary *params = [NSMutableDictionary dictionary];</div><div class="line">  [routerUrlComponents enumerateObjectsUsingBlock:</div><div class="line">   ^(NSString *routerComponent, NSUInteger idx, BOOL *stop) &#123;</div><div class="line">     </div><div class="line">     NSString *givenComponent = givenUrlComponents[idx];</div><div class="line">     //判断是否是形参，所以在注册路由时，一定要注意，参数以:开始，否则会当成路径字符串</div><div class="line">     if ([routerComponent hasPrefix:@&quot;:&quot;]) &#123;</div><div class="line">       //去除参数的:，然后将参数名作为 key，将对应的 givenComponent 作为值存入字典中，所以在调用路由的时候，传递参数（实参）顺序要一致，否则参数就错乱了</div><div class="line">       NSString *key = [routerComponent substringFromIndex:1];</div><div class="line">       [params setObject:givenComponent forKey:key];</div><div class="line">     &#125;</div><div class="line">     else if (![routerComponent isEqualToString:givenComponent]) &#123;</div><div class="line">       //在非传参数的情况下，如果路径不一致，则结束。结束后会去路由表中拿下一个路由来判断。</div><div class="line">       params = nil;</div><div class="line">       *stop = YES;</div><div class="line">     &#125;</div><div class="line">   &#125;];</div><div class="line">  return params;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;将路由跳转最重要的三个方法分析了一下，在重要的代码前都加上了注释。接下来总结一下整体的思路。</p>
<h2 id="五、总结"><a href="#五、总结" class="headerlink" title="五、总结"></a>五、总结</h2><p>&nbsp;&nbsp;注册的时候，比较简单，将我们的路径和 VC 传递进去，保存在字典中就可以了。跳转的时候，做的判断就比较多。首先判断缓存中是否有这个路径，如果有的话，直接跳转，在注释中也详细说明了为什么要缓存。如果没有的话，则去枚举这个路由字典，并组装数据，存入缓存中。</p>
<p>&nbsp;&nbsp;任何框架，都会有不完美的地方，没错，这里要说说了。如果需要给你跳转的 VC 传递数据，那么需要你的 VC 实现这个方法：<code>initWithRouterParams:params</code>，通过<code>params</code>去获取你的值。其实在这里也可以通过获取这个 VC 的所有属性，在创建这个 VC 的时候，通过 KVC 的方式把值赋给这个 VC 的属性。</p>
<p>&nbsp;&nbsp;另一种实现办法是扩展<code>UIViewController</code>，在这里可以这样做：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">@interface UIViewController (Routable)</div><div class="line"></div><div class="line">@property (nonatomic, strong) NSDictionary *params;</div><div class="line">@end</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">@implementation UIViewController (Routable)</div><div class="line"></div><div class="line">static char kAssociatedParamsObjectKey;</div><div class="line"></div><div class="line">- (void)setParams:(NSDictionary *)params&#123;</div><div class="line">    objc_setAssociatedObject(self, &amp;kAssociatedParamsObjectKey, params, OBJC_ASSOCIATION_RETAIN_NONATOMIC);</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSDictionary *)params</div><div class="line">&#123;</div><div class="line">    return objc_getAssociatedObject(self, &amp;kAssociatedParamsObjectKey);</div><div class="line">&#125;</div><div class="line"></div><div class="line">@end</div></pre></td></tr></table></figure>
<p>&nbsp;&nbsp;这样每个<code>UIViewController</code>中就不用实现固定的方法了，在使用的时候，直接调用<code>self.params</code>就可以拿到这个字典了。</p>
<h2 id="六、建议"><a href="#六、建议" class="headerlink" title="六、建议"></a>六、建议</h2><p>&nbsp;&nbsp;在<code>routable-ios</code>中给出的注册路由的方式是，一个 VC 一个 VC 的注册。可以将需要路由跳转的 VC 配置到 plist 文件中，写一个方法，读取 plist 文件，循环注册即可，在<code>application:didFinishLaunchingWithOptions:</code>方法中，调用注册路由的方法即可。</p>
<p>&nbsp;&nbsp;我 fork 了一份代码，并在里面添加了注释，想通过 Xcode 看的，可以下载下来看。 <a href="https://github.com/chenyu1520/routable-ios" target="_blank" rel="external">传送门</a></p>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/15/zhangjianfeng/web前端性能优化/" rel="prev">web前端性能优化</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/24/lixiaoqiang/ios中对象关联的底层实现/" rel="next">iOS源码解读-对象关联实现分析</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、routable-ios-是什么？可以用来做什么？与之类似的框架还有哪些？"><span class="nav-number">1.</span> <span class="nav-text">一、routable-ios 是什么？可以用来做什么？与之类似的框架还有哪些？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、routable-ios-中类的关系"><span class="nav-number">2.</span> <span class="nav-text">二、routable-ios 中类的关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、routable-ios-如何使用"><span class="nav-number">3.</span> <span class="nav-text">三、routable-ios 如何使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、routable-ios-中的核心类"><span class="nav-number">4.</span> <span class="nav-text">四、routable-ios 中的核心类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Routable"><span class="nav-number">4.1.</span> <span class="nav-text">1.Routable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-UPRouterOptions"><span class="nav-number">4.2.</span> <span class="nav-text">2.UPRouterOptions</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-RouterParams"><span class="nav-number">4.3.</span> <span class="nav-text">3.RouterParams</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-UPRouter"><span class="nav-number">4.4.</span> <span class="nav-text">4.UPRouter</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、总结"><span class="nav-number">5.</span> <span class="nav-text">五、总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、建议"><span class="nav-number">6.</span> <span class="nav-text">六、建议</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
